import { Service } from 'egg';
import { UserProps } from '../model/user';

export default class UserService extends Service {
  async createByEmail(payload: UserProps) {
    const { ctx } = this;
    const { username, password } = payload;
    const hash = await ctx.genHash(password!);
    const userCreatedData: Partial<UserProps> = {
      username,
      password: hash,
      email: username,
    };
    return await ctx.model.User.create(userCreatedData);
  }

  async findById(id: string) {
    return await this.ctx.model.User.findById(id);
  }

  async findByUsername(username: string) {
    return await this.ctx.model.User.findOne({ username });
  }

  async loginByCellphone(phoneNumber: string) {
    const { ctx, app } = this;
    const user = await this.ctx.model.User.findOne({ phoneNumber });
    if (user) {
      const token = app.jwt.sign(
        { username: user.username, _id: user._id },
        app.config.jwt.secret,
      );
      return token;
    }
    const userCreatedData: Partial<UserProps> = {
      username: phoneNumber,
      phoneNumber,
      nickName: `乐高${phoneNumber.slice(-4)}`,
      type: 'cellphone',
    };
    const newUser = await ctx.model.User.create(userCreatedData);
    const token = app.jwt.sign(
      { username: newUser.username },
      app.config.jwt.secret,
    );
    return token;
  }
}
